require('date-utils');
var models = require("../models"),
    Good = models.Good,
    Order = models.Order,
    User = models.User,
    UserDoctor = models.UserDoctor;
var util_wechat = require('../utils/wechatutil');
var settings = require('../config');
var randomstring = require("random-string");
var debug = require('debug')('wechat:buy');
var OAuth = require('wechat').OAuth;


module.exports = function (app) {

    /*成为咨询师*/
    app.post('/wcpay/becomedoctor', function (req, res) {
        var userDoctor = new UserDoctor();
/*        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                if (result) {
                    var openid = result.openid;*/
        //var openid=0;
                    //根据openid查询用户
        var openid = req.body.code;

           userDoctor.findUserByOpenid(openid, function (err, userDoctors) {
               var msg = 'exist';
               var result = '不可重复注册！';
               if (err || !userDoctors) {
                   userDoctor.username = req.body.username;
                   userDoctor.mobilephone = req.body.mobilephone;
                   userDoctor.email = req.body.email;
                   userDoctor.about = req.body.about;
                   userDoctor.wcopenid = openid;
                   userDoctor.fordate = new Date();
                   //userDoctor.state = 0;

                   userDoctor.saveUser(function(err) {
                      if(err) {
                          debug('insert user fail', err);
                          console.log("-------------------------------------"+err);
                          //res.end('fail');
                          msg = 'fail';
                          result = '抱歉！注册咨询师失败，请重试！'
                      }else {
                          msg = 'success';
                          result = '恭喜！注册成功，请等待审核！';
                      }
                       res.render("bdrs", {
                           title: "成为咨询师",
                           result: result,
                           msg: msg
                       });

                   });

               } else {
                   console.log('user is exist');
                   res.render("bdrs", {
                       title: "成为咨询师",
                       result: result,
                       msg: msg
                   });
               }
           })
      /*          }
            });
        }*/
    });
    app.get('/wcpay/becomedoctor', function (req, res) {
        var userDoctor = new UserDoctor();
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                if (result) {
                    var openid = result.openid;

                    res.render('bdoctor', {
                        title: '注册成为咨询师',
                        code: openid
                    });
                }
            });
        }

    });

    app.get("/wcpay/goodslist", function (req, res) {
        new Good().findGoods(function (err, goods) {
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                //res.redirect('wxpayjsapidemo.ejs')
                res.render("goodslist", {
                    title: "商品列表",
                    goods: goods
                })
            }
        })
    })

    app.get("/wcpay_test/goodslist", function (req, res) {
        new Good().findGoods(function (err, goods) {
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                //res.redirect('wxpayjsapidemo.ejs')
                res.render("wxpayjsapidemo", {
                    title: "商品列表",
                    goods: goods
                })
            }
        })
    })
    app.get("/wcpay/pay", function (req, res) {
        var goodid = req.query.goodid;
        new Good().findGoodById(goodid, function (err, good) {
            debug("the good", good);
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                //make tradeno
                var tradeno = randomstring({
                    length: 20,
                    numeric: true,
                    letters: false,
                    special: false
                });
                var new_payinfo = getpayinfo(settings.paySign, good.name, good.price, tradeno, req.ip);
                //生成订单
                var order = new Order();
                order.price = good.price;
                order.status = 0; //未支付
                order.date = (new Date().toFormat('YYYY-MM-DD HH24:MI:SS'));
                order.goodname = good.name;
                order.goodnumber = 1;
                order.tradeno = tradeno;
                order.servicecount = good.servicecount;
                order.saveOrder(order, function (err) {
                    if (err) {
                        debug("save order fail", err);
                        res.render("error", {
                            message: "出错啦",
                            error: err
                        })
                    } else {
                        res.render("pay", {
                            title: "购买商品",
                            good: good,
                            payinfo: JSON.stringify(new_payinfo),
                            tradeno: tradeno
                        });
                    }
                })

            }
        })
    })

    app.get("/wcpay/pay_end", function (req, res) {
        var tradeno = req.query.tradeno;
        new Order().updateOrderStatusByTradeno(tradeno, function (err, numberaffected) {
            if (err || numberaffected == 0) {
                debug("update order fail", err);
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                res.render("payend", {
                    title: "支付完成"
                });
            }
        })
    })

    app.get("/wcpay/orderlist", function (req, res) {
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                var openid;
                if (result) {
                    debug("get result is", result);
                    openid = result.openid;
                    if (openid) {
                        new User().findUserByOpenid(openid, function (err, user) {
                            if (err || !user) {
                                debug("findUserByOpenid fail", err);
                            } else {
                                new Order().findOrderByOpenId(openid, function (err, orders) {
                                    if (err) {
                                        debug("findOrderByOpenId fail", err);
                                        res.render("error", {
                                            message: "出错啦",
                                            error: err
                                        })
                                    } else {
                                        res.render("orderlist", {
                                            title: "订单查询",
                                            orders: orders,
                                            count: user.count
                                        });
                                    }
                                })
                            }
                        })
                    }
                } else {
                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }
            })
        }
    })
}

function getpayinfo(key, goodname, totalfee, tradeno, ip) {
    var wechat = new util_wechat();
    var tfee = String(totalfee * 100);
    debug("the trade totalfee:" + totalfee);
    var timestamp = String(Math.floor((new Date().getTime() / 1000))) //时间戳
    //pay info//pay info
    var payinfo = {
        "appid": "wx631f54c7933d782f",
        "appkey": "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB",
        "timestamp": timestamp,
        "noncestr": "5566521"
    };
    // pkg
    var pkg = {
        bank_type: "WX",
        body: goodname, //商品描述
        partner: settings.wc_partner, //注册时分配的财付通商户号 partnerId
        spbill_create_ip: ip, //用户浏览器IP
        total_fee: "1",
        fee_type: "1", //支付币种
        input_charset: "UTF-8", //传入参数字符 编码
        notify_url: "http://117.78.6.144/wcpay/notification/notify", //通知 URL
        out_trade_no: tradeno //商户订单号
    };


    //sort params
    var newpkg = wechat.sort(pkg);
    var newpkg_str = wechat.json2string(newpkg);
    debug("string1 sort : " + newpkg_str);

    //md5 the params string
    var mk5pkg_str = wechat.md5(newpkg_str + "&key=" + key).toUpperCase();
    debug("string1 md5 : " + mk5pkg_str);

    //encode the params value

    // var newpkg_encode = {};
    // _.each(newpkg, function(value, key, list) {
    //     newpkg_encode[key] = encodeURIComponent(value);
    // });

    var newpkg_encode = wechat.urlencode(newpkg);
    var newpkg_encode_str = wechat.json2string(newpkg_encode);
    debug("string1 encode : " + newpkg_encode_str);

    //add sign to package
    var package_str = newpkg_encode_str + "&sign=" + mk5pkg_str;
    debug("pay url : " + package_str);

    //update the package
    payinfo["package"] = package_str;

    //paysign string
    var newpayinfo = wechat.sort(payinfo);
    var newpayinfo_str = wechat.json2string(newpayinfo);
    debug("payinfo str:" + newpayinfo_str);

    //get the payinfo sha1
    var sha1_newpayinfo_str = wechat.sha1(newpayinfo_str);
    debug("payinfo sha1:" + sha1_newpayinfo_str);

    //add sha1 to the payinfo
    newpayinfo["signType"] = "SHA1";
    newpayinfo["paySign"] = sha1_newpayinfo_str;
    debug("add sign payinfo:", newpayinfo);


    //make the pramas to back
    newpayinfo["timeStamp"] = newpayinfo["timestamp"];
    newpayinfo["nonceStr"] = newpayinfo["noncestr"];
    newpayinfo["appId"] = newpayinfo["appid"];
    newpayinfo["appKey"] = newpayinfo["appkey"];
    delete newpayinfo["timestamp"];
    delete newpayinfo["noncestr"];
    delete newpayinfo["appid"];
    delete newpayinfo["appkey"];
    delete newpayinfo["appKey"];

    debug("lated payinfo:", newpayinfo);

    //return the result
    return newpayinfo;
}

var oldTimeStamp ;//记住timestamp，避免签名时的timestamp与传入的timestamp时不一致
var oldNonceStr ; //记住nonceStr,避免签名时的nonceStr与传入的nonceStr不一致

function getpayinfo(key, goodname, totalfee, tradeno, ip) {
    var wechat = new util_wechat();
    var tfee = String(totalfee * 100);
    debug("the trade totalfee:" + totalfee);
    //var timestamp = String(Math.floor((new Date().getTime() / 1000))) //时间戳
    //var timestamp = new Date().getTime().toString();
    //pay info//pay info
    var payinfo = {
        "appid": "wx631f54c7933d782f",
        "appkey": "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB",

        //"noncestr": "5566521"getNonceStr()
        "noncestr":getNonceStr(),
        "timestamp": timestamp
    };
    // pkg
    var pkg = {
        bank_type: "WX",
        body: goodname, //商品描述
        partner: settings.wc_partner, //注册时分配的财付通商户号 partnerId
        spbill_create_ip: ip, //用户浏览器IP
        total_fee: "1",
        fee_type: "1", //支付币种
        input_charset: "UTF-8", //传入参数字符 编码
        notify_url: "http://117.78.6.144/wcpay/notification/notify", //通知 URL
        out_trade_no: tradeno //商户订单号
    };
    var banktype = "WX";
    var body = goodname;//商品名称信息，这里由测试网页填入。
    var fee_type = "1";//费用类型，这里1为默认的人民币
    var input_charset = "UTF-8";//字符集，可以使用GBK或者UTF-8
    var notify_url = "http://117.78.6.144/wcpay/notification/notify";//支付成功后将通知该地址
    var out_trade_no = ""+getANumber();//订单号，商户需要保证该字段对于本商户的唯一性
    var partner = settings.wc_partner;//测试商户号
    var spbill_create_ip = ip;//用户浏览器的ip，这个需要在前端获取。这里使用127.0.0.1测试值
    var total_fee = 1;//总金额。
    var partnerKey = key;//这个值和以上其他值不一样是：签名需要它，而最后组成的传输字符串不能含有它。这个key是需要商户好好保存的。

    //首先第一步：对原串进行签名，注意这里不要对任何字段进行编码。这里是将参数按照key=value进行字典排序后组成下面的字符串,在这个字符串最后拼接上key=XXXX。由于这里的字段固定，因此只需要按照这个顺序进行排序即可。
    var signString = "bank_type="+banktype+"&body="+body+"&fee_type="
        +fee_type+"&input_charset="+input_charset+"&notify_url="+notify_url
        +"&out_trade_no="+out_trade_no+"&partner="+partner+"&spbill_create_ip="
        +spbill_create_ip+"&total_fee="+total_fee+"&key="+partnerKey;

    var md5SignValue =  ("" + wechat.md5(signString)).toUpperCase();
    //然后第二步，对每个参数进行url转码，如果您的程序是用js，那么需要使用encodeURIComponent函数进行编码。


    banktype = encodeURIComponent(banktype);
    body=encodeURIComponent(body);
    fee_type=encodeURIComponent(fee_type);
    input_charset = encodeURIComponent(input_charset);
    notify_url = encodeURIComponent(notify_url);
    out_trade_no = encodeURIComponent(out_trade_no);
    partner = encodeURIComponent(partner);
    spbill_create_ip = encodeURIComponent(spbill_create_ip);
    total_fee = encodeURIComponent(total_fee);

    //然后进行最后一步，这里按照key＝value除了sign外进行字典序排序后组成下列的字符串,最后再串接sign=value
    var completeString = "bank_type="+banktype+"&body="+body+"&fee_type="
        +fee_type+"&input_charset="+input_charset+"&notify_url="+notify_url
        +"&out_trade_no="+out_trade_no+"&partner="+partner+"&spbill_create_ip="
        +spbill_create_ip+"&total_fee="+total_fee;
    completeString = completeString + "&sign="+md5SignValue;

    payinfo["package"] = completeString;//package_str

    var app_id = getAppId().toString();
    var app_key = getAppKey().toString();
    var on
    var timestamp = getTimeStamp();

    //sign---!!!
    /*    var payinfo = {
     "appid": "wx631f54c7933d782f",
     "appkey": "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB",
     "timestamp": timestamp,
     //"noncestr": "5566521"getNonceStr()
     "noncestr":getNonceStr()
     };*/
    var keyvaluestring = "appid="+payinfo["appid"].toString+"&appkey="+payinfo["appkey"].toString+
        "&noncestr="+payinfo["noncestr"].toString+"&package="+completeString+"&timestamp="+timestamp;


    //get the payinfo sha1
    var sha1_newpayinfo_str = wechat.sha1(keyvaluestring);//newpayinfo_str
    debug("payinfo sha1:" + sha1_newpayinfo_str);

    //add sha1 to the payinfo
    newpayinfo["signType"] = "SHA1";
    newpayinfo["paySign"] = sha1_newpayinfo_str;
    debug("add sign payinfo:", newpayinfo);


    //make the pramas to back
    newpayinfo["timeStamp"] = newpayinfo["timestamp"];
    newpayinfo["nonceStr"] = newpayinfo["noncestr"];
    newpayinfo["appId"] = newpayinfo["appid"];
    newpayinfo["appKey"] = newpayinfo["appkey"];
    delete newpayinfo["timestamp"];
    delete newpayinfo["noncestr"];
    delete newpayinfo["appid"];
    delete newpayinfo["appkey"];
    delete newpayinfo["appKey"];

    debug("lated payinfo:", newpayinfo);

    //return the result
    return newpayinfo;
}

//商户生成的随机字符串
function getNonceStr(){
    var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var maxPos = $chars.length;
    var noceStr = "";
    for (i = 0; i < 32; i++) {
        noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    oldNonceStr = noceStr;
    return noceStr;
}

function getPartnerId()
{//替换partnerid
    return "1219234901";
}

function getPartnerKey()
{//替换partnerkey
    return "9764cc3c0dd67ca8940a7fa5e3047c9e";
}

function getAppId()
{//替换appid
    return "wx631f54c7933d782f";
}

function getAppKey()
{//替换appkey
    return "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB";
}

//获取随机数
function getANumber()
{
    var date = new Date();
    var times1970 = date.getTime();
    var times = date.getDate() + "" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds();
    var encrypt = times * times1970;
    if(arguments.length == 1){
        return arguments[0] + encrypt;
    }else{
        return encrypt;
    }

}
function getTimeStamp()
{
    var timestamp=new Date().getTime();
    var timestampstring = timestamp.toString();//一定要转换字符串
    oldTimeStamp = timestampstring;
    return timestampstring;
}